// Copyright (C) 2023 即时通讯网(52im.net) & Jack Jiang.
// The RainbowChat Project. All rights reserved.
// 
// 【本产品为著作权产品，合法授权后请放心使用，禁止外传！】
// 【本次授权给：<北京小羊驼科技有限公司>，授权编号：<NT231212144350>，代码指纹：<A.702363430.550>，技术对接人微信：<ID: wxid_wbyootvkdcgj22>】
// 【授权寄送：<收件：苏先生、地址：北京市大兴区北京密码西区6号楼1单元301、电话：18613885610、邮箱：bd@huiyuanxiang-inc.com>】
// 
// 【本系列产品在国家版权局的著作权登记信息如下】：
// 1）国家版权局登记名(简称)和权证号：RainbowChat    （证书号：软著登字第1220494号、登记号：2016SR041877）
// 2）国家版权局登记名(简称)和权证号：RainbowChat-Web（证书号：软著登字第3743440号、登记号：2019SR0322683）
// 3）国家版权局登记名(简称)和权证号：RainbowAV      （证书号：软著登字第2262004号、登记号：2017SR676720）
// 4）国家版权局登记名(简称)和权证号：MobileIMSDK-Web（证书号：软著登字第2262073号、登记号：2017SR676789）
// 5）国家版权局登记名(简称)和权证号：MobileIMSDK    （证书号：软著登字第1220581号、登记号：2016SR041964）
// * 著作权所有人：江顺/苏州网际时代信息科技有限公司
// 
// 【违法或违规使用投诉和举报方式】：
// 联系邮件：jack.jiang@52im.net
// 联系微信：hellojackjiang
// 联系QQ号：413980957
// 授权说明：http://www.52im.net/thread-1115-1-1.html
// 官方社区：http://www.52im.net
package com.x52im.mall.shop;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.Processor;
import com.eva.framework.dbpool.DBDepend;
import com.eva.framework.dbpool.DBShell;
import com.eva.framework.dto.SysActionConst;
import com.eva.framework.utils.EndsExceptionFactory;
import com.eva.framework.utils.ONHelper;
import com.eva.framework.utils.SNHelper;
import com.x52im.mall.shop.dto.Comment;
import com.x52im.mall.shop.dto.SO;
import com.x52im.mall.shop.dto.SOConsigneeInfo;
import com.x52im.mall.shop.dto.SODetail;

/**
 * 购物管理功能集业务处理器.
 * 
 * @author Jack Jiang(http://www.52im.net/space-uid-1.html)
 * @version 1.0
 */
public class ShopProcessor implements SysActionConst, Processor
{
	private static DBShell db = new DBShell();

	/**
	 * 处理器的核心实现方法.<br>
	 * 可据job_dispatch_id找到对应的JobDispatcher，JobDispatcher又能据
	 * action_id进行对应动作的处理，以完成本次操作请求.
	 * 
	 * @param job_dispatch_id 作业调度ID
	 * @param action_id 动作ID
	 * @param Object newData 客端发送过来的本次修改新数据(可能为空，理论上与oldData不会同时空）
	 * @param Object oldData 客端发送过来的本次修改前的老数据(可能为空，理论上与newData不会同时空）
	 * @param UserRoot user 包含该请求用户完整个人信息封装对象（该对象来自于成功登陆后存放于session中的值）
	 * @return 任意类型返回值
	 * @throws Exception
	 */
	@Override
	public Object process(int job_dispatch_id, int action_id, Object newData, Object oldData, User user) throws Exception
	{
		Object ret = null;
		switch (job_dispatch_id)
		{
		case com.x52im.mall.shop.dto.JobDispatchConst.SHOP_GOODS_MGR_NEED$AUTHED:
			ret = goodsMgrJobDispatcher(action_id, newData, oldData, user);
			break;
		default:
			throw EndsExceptionFactory.INVALID_JOB_DISPATCHER_ID(job_dispatch_id);
		}
		return ret;
	}

	/**
	 * 维护商品管理相关操作的作业调度.
	 * 
	 * @param action_id 维护类型，SysConstant中的操作类型常量
	 * @param newData 客端发送过来的本次修改新数据(可能为空，理论上与oldData不会同时空）
	 * @param oldData 客端发送过来的本次修改前的老数据(可能为空，理论上与newData不会同时空）
	 * @param userName 操作者的用户名
	 * @return 返回给客户端的对象
	 */
	@SuppressWarnings("unchecked")
	public Object goodsMgrJobDispatcher(int action_id, Object newData, Object oldData, User u) throws Exception
	{
		Vector sqls = new Vector(2);
		Vector values = new Vector(2);
		switch (action_id)
		{
			case ACTION_NEW:
			{
				SO so = (SO) newData;
				String orderId = ONHelper.getON("sales_so_order_id");
				so.setOrder_id(orderId);
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String sign = CommonUtils.getRandomStr2(20);
				sqls.add("INSERT INTO sales_so(order_id,order_type,for_user_uid," +
						"order_date,order_status,pay_type,order_currency," +
						"order_amount,transfer_id,fare_amount,order_total,pay_time,appender,sign,create_time)" +
						"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,"+DBDepend.getDefaultDatetimeFunc()+")");
				values.add(new Object[] {
							orderId,so.getOrder_type(),so.getFor_user_uid(),sdf.format(date),
							so.getOrder_status(),so.getPay_type(),so.getOrder_currency(),
							so.getOrder_amount(),so.getTransfer_id(),so.getFare_amount(),
							so.getOrder_total(),so.getPay_time(),so.getAppender(),sign
				});
				List<SODetail> details = so.getSoDetails();
				for(SODetail d : details){
					sqls.add("INSERT INTO sales_so_detail(so_detail_id,order_id," +
							"device_id,color_id,purchase_quantity,purchase_price," +
							"purchase_amount,appender)" +
							"VALUES(?,?,?,?,?,?,?,?)");
					values.add(new Object[] {
							SNHelper.getSN("sales_so_detail_id"),orderId,d.getDevice_id(),
							d.getColor_id(),d.getPurchase_quantity(),d.getPurchase_price(),
							d.getPurchase_amount(),d.getAppender()
					});
				}
				SOConsigneeInfo ci = so.getSoConsigneeInfo();
				sqls.add("INSERT INTO sales_so_consignee_info(order_id,consignee_surname," +
						"consignee_name,country_of_consignee,city_of_consignee,addr_of_consignee," +
						"code_of_consignee,mail_of_consignee,phone_of_consignee,appender) " +
						"VALUES(?,?,?,?,?,?,?,?,?,?)");
				values.add(new Object[] {
						orderId,ci.getConsignee_surname(),ci.getConsignee_name(),
						ci.getCountry_of_consignee(),ci.getCity_of_consignee(),ci.getAddr_of_consignee(),
						ci.getCode_of_consignee(),ci.getMail_of_consignee(),ci.getPhone_of_consignee(),
						ci.getAppender()
				});
				
				boolean res = db.update(sqls, values, true);
				if(res)
				{
					//#### 20180316 by Jack Jiang：因商城功能当前仅作演示，为了简化代码，下单发邮件的能力暂时取消！
//					// 邮件正文
//					String inviteMainContent = BaseConf.getInstance().getSNS_PLACE_ORDER_CONTENT(orderId);
//
//					OutgoingMail om = new OutgoingMail(
//							BaseConf.getInstance().getSNS_INVITE_SMTP_SERVER(), 
//							BaseConf.getInstance().getSNS_INVITE_MASTER_EMAIL_ADDR(),
//							BaseConf.getInstance().getSNS_INVITE_MASTER_NICK_NAME(), 
//							BaseConf.getInstance().getSNS_INVITE_MASTER_EMAIL_NAME(), 
//							BaseConf.getInstance().getSNS_INVITE_MASTER_EMAIL_PASSWORD(), 
//							ci.getMail_of_consignee(), 
//							BaseConf.getInstance().getSNS_PLACE_ORDER_SUBJECT(),
//							inviteMainContent);
//					// om.addAttachfile("C:\\js4713.txt");
//
//					// 发送邮件
//					try
//					{
//						HashMap hm = om.send();
//						if (hm.get("message") != null)// 发送成功了
//							System.out.println("发送成功");
//						else
//							System.out.println("发送失败");
//						}
//					catch(Exception e)
//					{
//						LoggerFactory.getLog().error(e.getMessage(), e);
//					}
					
					so.setSign(sign);
					return so;
				}
				return null;
			}
			//查询订单明细数据
			case ACTION_APPEND2:
			{
				String sql = "SELECT " +
									"order_id,order_type,for_user_uid," +
									"order_date,order_status,pay_type," +
									"order_currency,order_amount,transfer_id," +
									"fare_amount,order_total,create_time,pay_time,appender,sign " +
									"FROM sales_so " +
							"WHERE for_user_uid = '" + newData+"' order by create_time desc";
				
				Vector<Vector> vec = db.queryData(sql);
				ArrayList<SO> datas = new ArrayList<SO>();
				if(vec.size() > 0)
				{
					for(Vector row : vec)
					{
						int j = 0;
						SO d = new SO();
						d.setOrder_id((String)row.get(j++));
						d.setOrder_type((String)row.get(j++));
						d.setFor_user_uid((String)row.get(j++));
						d.setOrder_date((String)row.get(j++));
						d.setOrder_status((String)row.get(j++));
						d.setPay_type((String)row.get(j++));
						d.setOrder_currency((String)row.get(j++));
						d.setOrder_amount((String)row.get(j++));
						d.setTransfer_id((String)row.get(j++));
						d.setFare_amount((String)row.get(j++));
						d.setOrder_total((String)row.get(j++));
						d.setCreate_time((String)row.get(j++));
						d.setPay_time((String)row.get(j++));
						d.setAppender((String)row.get(j++));
						d.setSign((String)row.get(j++));
						
						d.setSoDetails(getSODetails(d.getOrder_id()));
						d.setSoConsigneeInfo(getSOConsigneeInfo(d.getOrder_id()));
						datas.add(d);
					}
				}
				
				return datas;
			}
			case ACTION_APPEND3 :
			{
				Comment comment = (Comment)newData;
				sqls.add("INSERT INTO device_evaluate(device_id,for_user_uid,so_detail_id,eva_content,eva_score) VALUES(?,?,?,?,?)");
				sqls.add("UPDATE sales_so_detail SET is_evaluate=1 WHERE so_detail_id=?");
				values.add(new Object[] {
						comment.getDevice_id(),comment.getFor_user_uid(),comment.getSo_detail_id(),comment.getEva_content(),comment.getEva_score()
				});
				
				values.add(new Object[] {
						comment.getSo_detail_id()
				});
				
				return db.update(sqls, values, true);
			}
			case ACTION_APPEND4 :
			{
				return getSODetails(String.valueOf(newData));
			}
			case ACTION_EDIT :
			{
				SO so = (SO) newData;
				sqls.add("UPDATE sales_so SET order_status=?,pay_time="+DBDepend.getDefaultDatetimeFunc()
						+",pay_key=? WHERE order_id=? and order_status=0 and sign=?");
				values.add(new Object[] {
						so.getOrder_status(),so.getPay_key(),so.getOrder_id(),so.getSign()
				});
				
				return db.update(sqls, values, true);
			}
	
			default:
				throw EndsExceptionFactory.INVALID_ACTION_ID(action_id);
		}
	}
	
	public static ArrayList<SODetail> getSODetails(String order_id) throws Exception{
		ArrayList<SODetail> datas = new ArrayList<SODetail>();
		String sql = "SELECT " +
							"so_detail_id,order_id,device_id," +
							"color_id,purchase_quantity,purchase_price,is_evaluate,appender " +
					"FROM sales_so_detail " +
					"WHERE order_id = '" + order_id + "'";
		Vector<Vector> vec = db.queryData(sql);
		if(vec.size() > 0)
		{
			for(Vector row : vec)
			{
				int j = 0;
				SODetail d = new SODetail();
				d.setSo_detail_id((String)row.get(j++));
				d.setOrder_id((String)row.get(j++));
				d.setDevice_id((String)row.get(j++));
				d.setColor_id((String)row.get(j++));
				d.setPurchase_quantity((String)row.get(j++));
				d.setPurchase_price((String)row.get(j++));
				d.setIs_evaluate((String)row.get(j++));
				d.setAppender((String)row.get(j++));
				datas.add(d);
			}
		}
		return datas;
	}
	
	public static SOConsigneeInfo getSOConsigneeInfo(String order_id) throws Exception{
		String sql = "SELECT " +
							"order_id,consignee_surname,consignee_name," +
							"country_of_consignee,city_of_consignee,addr_of_consignee," +
							"code_of_consignee,mail_of_consignee,phone_of_consignee,appender " +
					"FROM sales_so_consignee_info " +
					"WHERE order_id = '" + order_id + "'";
		SOConsigneeInfo d = new SOConsigneeInfo();
		Vector<Vector> vec = db.queryData(sql);
		for(Vector row : vec)
		{
			int j = 0;
			d.setOrder_id((String)row.get(j++));
			d.setConsignee_surname((String)row.get(j++));
			d.setConsignee_name((String)row.get(j++));
			d.setCountry_of_consignee((String)row.get(j++));
			d.setCity_of_consignee((String)row.get(j++));
			d.setAddr_of_consignee((String)row.get(j++));
			d.setCode_of_consignee((String)row.get(j++));
			d.setMail_of_consignee((String)row.get(j++));
			d.setPhone_of_consignee((String)row.get(j++));
			d.setAppender((String)row.get(j++));
		}
		return d;
	}
}
